package server;

import java.util.HashMap;

import peer.tools.Mdb;


public class CleanTaskMange implements Runnable{
	Thread mainThread;
	HashMap<CleanTaskIdent, CleanTask> cleanTaskTable;
	HashMap<Long, TimeMap> timeMapTable;
	CleanTaskMange(){
		cleanTaskTable=new HashMap<CleanTaskIdent, CleanTask>();
		timeMapTable=new HashMap<Long, TimeMap>();
		mainThread=new Thread (this);
		mainThread.start();
	}
	
	void addCleanTask(Mdb mdb,int sourceSessionId){
		CleanTaskIdent cti=new CleanTaskIdent(mdb,sourceSessionId);
		long nowTime=System.currentTimeMillis()/1000;
		CleanTask ct=new CleanTask(mdb,sourceSessionId,nowTime);
		cleanTaskTable.put(cti, ct);
		for(int i=0;i<3;i++){
			long insertTime=nowTime+i*20;
			if(!timeMapTable.containsKey(insertTime)){
				TimeMap tm=new TimeMap(insertTime);
				timeMapTable.put(insertTime, tm);
			}
			TimeMap tm=timeMapTable.get(insertTime);
			tm.addCleanTask(cti);
			ct.runCount++;
		}
	}
	
	CleanTask getCleanTask(CleanTaskIdent cti){
		return cleanTaskTable.get(cti);
	}
	
	void removeCleanTask(Mdb mdb,int sourceSessionId){
		CleanTaskIdent cti=new CleanTaskIdent(mdb,sourceSessionId);
		cleanTaskTable.remove(cti);
	}
	
	void removeCleanTask(CleanTaskIdent cti){
		cleanTaskTable.remove(cti);
	}
	
	boolean containsCleanTask(Mdb mdb,int sourceSessionId){
		CleanTaskIdent cti=new CleanTaskIdent(mdb,sourceSessionId);
		return cleanTaskTable.containsKey(cti);
	}
	
	boolean containsCleanTask(CleanTaskIdent cti){
		return cleanTaskTable.containsKey(cti);
	}
	
	public void run(){
		while(true){
			long scanTime=System.currentTimeMillis()/1000-1;
			TimeMap tm=timeMapTable.get(scanTime);
			if(tm!=null){
				tm.cleanAll();
				timeMapTable.remove(scanTime);
			}
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
